<?php
// 应用公共文件
use think\facade\Db;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use create_order_number\SnowFlake;
use OSS\OssClient;
use OSS\Core\OssException;

/**
*阿里云存储oss
*$folder Bucket下的项目文件夹
*$filesize int  文件大小 单位B
*$fileExt  string 文件的后缀名
**/
 function aliyunOssUpload($folder,$filesize,$fileExt){
	// 获取表单上传文件 例如上传了001.jpg
	$file = request()->file('file');
	$ext = strrchr($file->getOriginalName(), '.');
	$object = $folder.'/'.date('YmdHis').mt_rand(000, 999).$ext;
	// <yourLocalFile>由本地文件路径加文件名包括后缀组成，例如/users/local/myfile.txt。
	// 填写本地文件的完整路径，例如D:\\localpath\\examplefile.txt。如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件。
	//$filePath = $file->getLinkTarget();
	$filePath =  $_FILES['file']["tmp_name"];
	try {
		//20M
		validate(['file'=>['filesize'=>$filesize, 'fileExt'=>$fileExt]])->check(['file'=>$file]);
		$ossClient = new OssClient(config('aliyun_oss')['accessKeyId'],config('aliyun_oss')['accessKeySecret'], config('aliyun_oss')['endpoint']);
		$oss_data = $ossClient->uploadFile(config('aliyun_oss')['bucket'], $object, $filePath);
		return [
			'status'=>200,
			'msg'=>'上传成功',
			'path'=>$oss_data['oss-request-url']
		];
	} catch (\think\exception\ValidateException $e) {
		return ['status'=>500,'msg'=>$e->getMessage(),'path'=>''];
	}		 
 }

/**
 * 获取客户端IP地址
 * @param int $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @param bool $adv 是否进行高级模式获取（有可能被伪装）
 * @return mixed
 */
function getIP($type = 0, $adv = false)
{
	$type = $type ? 1 : 0;
	static $ip = NULL;
	if ($ip !== NULL) return $ip[$type];
	if ($adv) {
		if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
			$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
			$pos = array_search('unknown', $arr);
			if (false !== $pos) unset($arr[$pos]);
			$ip = trim($arr[0]);
		} elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
			$ip = $_SERVER['HTTP_CLIENT_IP'];
		} elseif (isset($_SERVER['REMOTE_ADDR'])) {
			$ip = $_SERVER['REMOTE_ADDR'];
		}
	} elseif (isset($_SERVER['REMOTE_ADDR'])) {
		$ip = $_SERVER['REMOTE_ADDR'];
	}
	// IP地址合法验证
	$long = sprintf("%u", ip2long($ip));
	$ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
	return $ip[$type];
}
 /**
 * 由 getSort($data,$f_id=0,$level=1){
 *  static $arr =array();
 *  foreach($data as $key=>$value){
 *      if($value[$fid_field]==$f_id){
 *          $value[$level_field]=$level;
 *          $arr[] =$value;
 *          getSort($data,$value['id'],$level+1)
 *      }
 *   }
 *   return $arr;
 * }
 * 此方法使用递归，慎用
 * 返回id和fid对应【排序】
 * $data table表的数据数组
 * $id_field table表的id字段名
 * $fid_field table表的 f_id 字段名
 * $level_field table表的level字段名
 * $f_id=0 默认刚开始查找父级id为0的数据
 * $level 默认刚开始查找父级层级为1的数据
 *
 **/
function getSort(array $data,string $id_field,string $fid_field,string $level_field,$f_id=0,$level=1){
	static $arr =array();
	foreach($data as $key=>$value){
		if($value[$fid_field]==$f_id){
			$value[$level_field]=$level;
			$arr[] =$value;
			//开始递归,查找父ID为该节点ID的节点,级别则为原级别+1
			getSort($data,$id_field,$fid_field,$level_field,$value[$id_field],$level+1);
		}
	}
	return $arr;
}
/**
 *
 * 此方法使用递归，慎用
 * 返回id父级以下的所有fid对应
 * $data table表的数据数组
 * $id_field table表的id字段名
 * $fid_field table表的 f_id 字段名
 * $f_id=0 默认刚开始查找父级id为0的数据
 *
 **/
function getTree(array $data,$id_field,$fid_field,$f_id = 0)
{
	$list = [];
	foreach ($data as $value) {
		//第一次遍历，找到父节点为0的
		if ($value[$fid_field] == $f_id) {
			//开始递归，查找父id为该节点id的节点
			if (!empty(getTree($data,$id_field,$fid_field,$value[$id_field]))) {
				$value['children'] = getTree($data,$id_field,$fid_field, $value[$id_field]);
			}
			$list[] = $value;
		}
	}
	return $list;
}
/**
*设置成功返回值 
**/
function success($type_msg='',$data='',$status=200){
	$result = ['status'=>$status,'msg'=>$type_msg.'成功','data'=>$data];
	echo json_encode($result);
	exit();
}
/**
*设置失败返回值 
**/
function fail($type_msg='',$data='',$status=500){
	$result = ['status'=>$status,'msg'=>$type_msg.'失败','data'=>$data];
	echo json_encode($result);
	exit();
}
/**
 * 防止注入xss
 * $dirty_html 用户上传的值
**/
function Xss($dirty_html){
//        $dirty_html=<<<EOF
//        <h1>Hello
//        <script>alert("world");</script>
//EOF;
	$config = HTMLPurifier_Config::createDefault();
	$purifier = new HTMLPurifier($config);
	$clean_html = $purifier->purify($dirty_html);
	return $clean_html;
}
/**
 * 将万和亿简写成小数点
 * $num 数字
 **/
function float_mo($num){
	$num_len = strlen($num);
	if($num_len>=5&&$num_len<9){
		return round($num/10000, 2).'万';
	}else if($num_len>=9){
		return round($num/100000000, 2).'亿';
	}else{
		return $num;
	}
}


/**
 * 文件地址
 * 截取url可删除
 * $url url地址
 **/
function cutOutUrl($url){
	//去掉\
	$url = str_replace("\\","",$url);
	$del_url = public_path().substr($url,strpos($url,'/',8));
	//去掉 //
	$del_url = str_replace("//","/",$del_url);
	$url = substr($url,strpos($url,'/',8));
	return array('del_url'=>$del_url,'url'=>$url);
}
/**
 * 私密 隐藏 隐私 姓名
 * 姓名隐藏后面
 * 卜**
 * $userName 用户姓名
 **/
function substrCut($userName)
{
	$strlen = mb_strlen($userName, 'utf-8');
	$firstStr = mb_substr($userName, 0, 1, 'utf-8');
	$lastStr = mb_substr($userName, -1, 1, 'utf-8');
	//若名字长度==2，则 姓** 否则姓*名
	//$resultName = ($strlen == 2) ? $firstStr . str_repeat('**', mb_strlen($userName, 'utf-8') - 1) : $firstStr . str_repeat("*", $strlen - 2). $lastStr ;
	//全设为姓**
	$resultName = ($strlen == 2) ? $firstStr . str_repeat('**', mb_strlen($userName, 'utf-8') - 1) : $firstStr . str_repeat("*",  2) ;
	return $resultName;
}
/**
 * 私密 隐藏 隐私 手机号码
 * 手机号码隐藏4位中间
 * 176****3972
 * $userPhone 电话号码
**/
function substrPhone($userPhone)
{
	$strlen = mb_strlen($userPhone, 'utf-8');
	$firstStr = mb_substr($userPhone, 0, 3, 'utf-8');
	$lastStr = mb_substr($userPhone, 7, 4, 'utf-8');

	$resultPhone =  $firstStr . str_repeat("*", $strlen - 7).$lastStr;
	return $resultPhone;
}

/**
 *将时间转为几秒钟，几分钟
 *
 */
function time_ago($posttime){
	//当前时间的时间戳
	$nowtimes = strtotime(date('Y-m-d H:i:s'),time());
	//之前时间参数的时间戳
	$posttimes = strtotime($posttime);
	//相差时间戳
	$counttime = $nowtimes - $posttimes;
	//进行时间转换
	if($counttime<=10){
		return '刚刚';
	}else if($counttime>10 && $counttime<=30){
		return '刚才';
	}else if($counttime>30 && $counttime<=60){
		return '刚一会';
	}else if($counttime>60 && $counttime<=120){
		return '1分钟前';
	}else if($counttime>120 && $counttime<=180){
		return '2分钟前';
	}else if($counttime>180 && $counttime<3600){
		return intval(($counttime/60)).'分钟前';
	}else if($counttime>=3600 && $counttime<3600*24){
		return intval(($counttime/3600)).'小时前';
	}else if($counttime>=3600*24 && $counttime<3600*24*2){
		return '昨天';
	}else if($counttime>=3600*24*2 && $counttime<3600*24*3){
		return '前天';
	}else if($counttime>=3600*24*3 && $counttime<=3600*24*20){
		return intval(($counttime/(3600*24))).'天前';
	}else{
		return $posttime;
	}
}

/**
 * 获取富文本编译器中的所有图片
 * @param string $contentStr
 * @return array
 */
function getPatternMatchImages($contentStr = "")
{
	$img_src_arr = [];
	$pattern_imgTag = '/<img\b.*?(?:\>|\/>)/i';
	preg_match_all($pattern_imgTag,$contentStr,$match_img);
	if (isset($match_img[0]))
	{
		foreach ($match_img[0] as $key => $img_tag)
		{
			$pattern_src = '/\bsrc\b\s*=\s*[\'\"]?([^\'\"]*)[\'\"]?/i';
			preg_match_all($pattern_src,$img_tag,$matchSrc);
			if (isset($matchSrc[1]))
			{
				foreach ($matchSrc[1] as $src)
				{
					$img_src_arr[] = $src;
				}
			}
		}
	}
	return $img_src_arr;
}
/**
 * 云信通短信平台api
 *查询短信剩余量
 *  $userName 账户名
 *  $pssword 密码
*/
function getMessageSum($userName,$password){
    /**{"code":0,"message":"处理成功","balance":1}**/
    $url = "http://119.23.144.191:8001/sms/api/getBalance";
    $udata = [];
    $udata['userName'] = $userName;
    $udata['timestamp'] =msectimes();//ms //strtotime(date("Y-m-d H:i:s"))*100
    $udata['sign'] = md5($udata['userName'].$udata['timestamp'].md5($password));
    $header = [
        'Accept:application/json',
        'Content-Type:application/json;charset=utf-8'
    ];
    $res = req_Posts($url,$header,json_encode($udata));
    return $res;
}

/**
 * 云信通短信平台api
 *一条短信发给一个人
 *  $userName 账户名
 *  $pssword 密码
 *  $phone 发送的手机号码
 *  $content 发送的内容 【必须给短信平台备案才可以发送】
*/

function shortMessage(string $userName,string $pssword,string $phone,string $content){
    $url = "http://119.23.144.191:8001/sms/api/sendMessageOne";
    $udata = [];
    $udata['userName'] = $userName;
    $udata['pssword'] = $pssword;
    $udata['messageList'] =array(['phone'=>(string)$phone,'content'=>$content]);
    $udata['timestamp'] =msectimes();//ms //strtotime(date("Y-m-d H:i:s"))*100
    $udata['sign'] = md5($udata['userName'].$udata['timestamp'].md5($udata['pssword']));
    $header = [
        'Accept:application/json',
        'Content-Type:application/json;charset=utf-8'
    ];
    $res = req_Posts($url,$header,json_encode($udata));
    return $res;
}
/**
 * 云信通短信平台api
 * 一条短信发给多个人
 *  $userName 账户名
 *  $pssword 密码
 *  $phoneList array 发送的多人手机号码
 *  $content 发送的内容 【必须给短信平台备案才可以发送】
 */
function moreMessage(string $userName,string $password,array $phoneList,string $content){
    $url = "http://119.23.144.191:8001/sms/api/sendMessage";
    $udata = [];
    $udata['userName'] = $userName;
    $udata['content'] = $content;
    $udata['phoneList'] = $phoneList;
    $udata['timestamp'] =msectimes();//ms //strtotime(date("Y-m-d H:i:s"))*100
    $udata['sign'] = md5($udata['userName'].$udata['content'].$udata['timestamp'].md5($password));
    $header = [
        'Accept:application/json',
        'Content-Type:application/json;charset=utf-8'
    ];
    $res = req_Posts($url,$header,json_encode($udata));
    return $res;
}
//返回当前的毫秒时间戳
function msectimes(){
    list($msec, $sec) = explode(' ', microtime());
    $msectime = (int)sprintf('%.0f',(floatval($msec) + floatval($sec)) * 1000);
    return $msectime;
}
//php发送Post带header头部请求
function req_Posts($url,$header,$udata)
{
    $timeout = 5;
    $con = curl_init();
    curl_setopt($con, CURLOPT_URL, $url);
    curl_setopt($con, CURLOPT_FORBID_REUSE, 1);
    curl_setopt($con, CURLOPT_FRESH_CONNECT, 1);
    curl_setopt($con, CURLINFO_HEADER_OUT, true);
    curl_setopt($con, CURLOPT_HTTPHEADER, $header);
    curl_setopt($con, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($con, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($con, CURLOPT_POST,true);
    curl_setopt($con, CURLOPT_POSTFIELDS,$udata);//http_build_query($udata)param1=value1&param2=value2
    curl_setopt($con, CURLOPT_HEADER, false);
    curl_setopt($con, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($con, CURLOPT_TIMEOUT, (int)$timeout);
    $p_res = curl_exec($con);
     //$a = curl_getinfo($con, CURLINFO_HEADER_OUT);
     //dump('头部信息',$a);
    curl_close($con);
    //return $p_res;
    if ($p_res) {
        return $p_res;
    } else {
        return false;
    }
}
/**
 * 创建qc二维码
*/
function create_qrcode($value,$file_name){
    include_once '../extend/qrcode/phpqrcode.php';
    $errorCorrectionLevel='L';//容错级别
    $matrixPointSize = 5;//生成图片大小
    $file_dir = public_path().'qrcode';
    if(!is_dir($file_dir)){
        mkdir($file_dir,0777, true);
    }
    $filename='qrcode/'.$file_name.'.png';
    \QRcode::png($value,$filename,$errorCorrectionLevel,$matrixPointSize,2);
    $path=$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/'.$filename;
    //echo '<img src='.$path.'>';
    return $path;
}

/**
 * 生成随机字符串
 * $srtLength int 取的字符串长度
*/
function rand_code($srtLength=32)
{
    $str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $str = str_shuffle($str);
    $str = substr($str, 0, $srtLength);
    return $str;
}

/**
 * php发送curl的get请求
 * $curl：url地址
 */
function req_Get($curl)
{
    if ($curl == "") {
        return false;
    }
    $timeout = 5;
    $con = curl_init();
    curl_setopt($con, CURLOPT_URL, $curl);
    curl_setopt($con, CURLOPT_HEADER, false);
    curl_setopt($con, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($con, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($con, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($con, CURLOPT_TIMEOUT, (int)$timeout);
    $c_res = curl_exec($con);
    curl_close($con);
    if ($c_res) {
        return $c_res;
    } else {
        return false;
    }
}

/**
 * php发送curl的Post请求
 * $url：url地址
 * $udata 发送的post值
 */
function req_Post($url, $udata)
{
    $timeout = 5;
    $con = curl_init();
    curl_setopt($con, CURLOPT_URL, $url);
    curl_setopt($con, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($con, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($con, CURLOPT_POST, true);
    curl_setopt($con, CURLOPT_POSTFIELDS, $udata);
    curl_setopt($con, CURLOPT_HEADER, false);
    curl_setopt($con, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($con, CURLOPT_TIMEOUT, (int)$timeout);
    $p_res = curl_exec($con);
    curl_close($con);
    if ($p_res) {
        return $p_res;
    } else {
        return false;
    }
}
/**
 * 文件上传
 * $fileSize：文件大小（传入int类型，单位:B）
 * $fileType 文件类型 （传入sting类型）
*/
function fileUpload($fileSize,$fileType){
    // 获取表单上传文件 例如上传了001.jpg
    $file = request()->file('file');
    try {
        //10M
        validate(['file'=>['filesize'=>$fileSize, 'fileExt'=>$fileType]])->check(['file'=>$file]);
        // 输出uploads/20220608\\2a412343630adc2b67d3d3e2c723a2cd.jpg
        $img_url= \think\facade\Filesystem::disk('public')->putFile( 'uploads', $file);
        $savename =  str_replace('\\', '/', $img_url);
        // 输出 http://127.0.0.1/public/storage/uploads/20220608\\2a412343630adc2b67d3d3e2c723a2cd.jpg
        $url = $_SERVER['REQUEST_SCHEME']."://".$_SERVER['HTTP_HOST'].'/storage/'.$savename;
        $carousel_url_name = '/storage/'.$savename;
        return ['status'=>200,'msg'=>'上传成功！','path'=>$url,'del_url'=>$carousel_url_name];

    } catch (\think\exception\ValidateException $e) {
        return ['status'=>500,'msg'=>$e->getMessage(),'path'=>''];
    }
}

/**
 *注意：若是用在for循环必须单独写不可直接调用，
 *且在for外面new实例化
 * 订单号
 * 雪花算法生成唯一id测试中: string
 * 返回24位数字
*/
function genAppNo(){
    $datacenterId = rand(1, 4);//数据id
    $machineId = rand(1,31);//机器id
    $sf = new SnowFlake($datacenterId, $machineId);
    $nextId = strval($sf->nextId());
    return date("ymdHis").substr($nextId, 6);
}
/**
 * 导入sheet单张工作表数量excel数据
 *  根据业务注意修改$city的内容
*/
function importExcel(){
    $file = request()->file('file');
    $savename = [];
    try {

        // 验证文件大小，名称等是否正确10M
        validate(['file'=>['filesize'=>10485760, 'fileExt'=>'xls,xlsx']])->check(['file'=>$file]);
        // 将文件保存到本地
        $savename= \think\facade\Filesystem::disk('public')->putFile( 'topic', $file);
        // 截取后缀
        $fileExtendName = substr(strrchr($savename, '.'), 1);
        // 有Xls和Xlsx格式两种
        if ($fileExtendName == 'xlsx') {
            $reader = IOFactory::createReader('Xlsx');
        } else {
            $reader = IOFactory::createReader('Xls');
        }

        $reader->setReadDataOnly(TRUE);//忽略任何格式的信息
        $spreadsheet = $reader->load(public_path() . 'storage/' . $savename); //载入excel表格
        $worksheet = $spreadsheet->getActiveSheet();//获取数据
        $sheet = $spreadsheet->getSheet(0);   //excel中的第一张sheet
        $highestRow = $worksheet->getHighestRow(); // 总行数
        $highestColumn = $worksheet->getHighestColumn(); // 总列数
        Coordinate::columnIndexFromString($highestColumn);
        $lines = $highestRow - 1;
        if ($lines <= 0) {
            return ['status'=>500,'msg'=>'数据不能为空！'];
            exit();
        }
        // 直接取出excle中的数据
        $data = $spreadsheet->getActiveSheet()->toArray();
        // 删除第一个元素（表头）
        array_shift($data);
        $city = [];
        foreach($data as $k=>$v) {
            $city[$k]['activity_name'] = $v[0];
            $city[$k]['user_name'] = $v[1];
            $city[$k]['user_phone'] = $v[2];
            $city[$k]['user_company'] = $v[3];
            $city[$k]['user_post'] = $v[4];
        }
        Db::table("activity")->insertAll($city);
        try {
            return ['status'=>200,'msg'=>'数据导入成功！'];
        } catch (Exception $e) {
            return ['status'=>500,'msg'=>$e->getMessage()];
        }


    } catch (ValidateException $e) {
        return json(['status'=>500,'data'=>$e->getMessage()]);
    }
}
/**
 * excel导出带图片
 * $data array or objArray 表数据
**/
function exporttest($data){
    set_time_limit(0);
    if (!$data) {
        /*****发生意外错误*****/
        throw  new APIExceptionHandler('错误');
    }
    $newExcel = new Spreadsheet();             //创建一个新的excel文档
    $objSheet = $newExcel->getActiveSheet();   //获取当前操作sheet的对象
    $objSheet->setTitle('订单表');             //设置当前sheet的标题

    // 将默认字体设置为Arial
    $newExcel->getDefaultStyle()->getFont()->setName('微软雅黑');
    // 将字体大小设置为12
    $newExcel->getDefaultStyle()->getFont()->setSize(12);
    // 将D列单元格设置为粗体字
//        $newExcel->getActiveSheet()->getStyle('H')->getFont()->setBold(true);
    // 设置默认行高为60
    $newExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(50);

    // 给标题单元格设置水平垂直居中对齐
    $newExcel->getActiveSheet()->getStyle('A:B')->getAlignment()->setHorizontal('center');
    $newExcel->getActiveSheet()->getStyle('A:B')->getAlignment()->setVertical('center');

    // 给每列单元格设置宽度
    $newExcel->getActiveSheet()->getColumnDimension('A')->setWidth(8);
    $newExcel->getActiveSheet()->getColumnDimension('B')->setWidth(8);
//        $newExcel->getActiveSheet()->getColumnDimension('C')->setWidth(40);
//        $newExcel->getActiveSheet()->getColumnDimension('D')->setWidth(10);
//        $newExcel->getActiveSheet()->getColumnDimension('E')->setWidth(8);
//        $newExcel->getActiveSheet()->getColumnDimension('F')->setWidth(15);
//        $newExcel->getActiveSheet()->getColumnDimension('G')->setWidth(15);
//        $newExcel->getActiveSheet()->getColumnDimension('H')->setWidth(15);
//        $newExcel->getActiveSheet()->getColumnDimension('I')->setWidth(20);
//        $newExcel->getActiveSheet()->getColumnDimension('J')->setWidth(30);
//        $newExcel->getActiveSheet()->getColumnDimension('K')->setWidth(10);
//        $newExcel->getActiveSheet()->getColumnDimension('L')->setWidth(10);
//        $newExcel->getActiveSheet()->getColumnDimension('M')->setWidth(15);
//        $newExcel->getActiveSheet()->getColumnDimension('N')->setWidth(15);
//        $newExcel->getActiveSheet()->getColumnDimension('O')->setWidth(15);
//        $newExcel->getActiveSheet()->getColumnDimension('P')->setWidth(10);
//        $newExcel->getActiveSheet()->getColumnDimension('Q')->setWidth(50);
//        $newExcel->getActiveSheet()->getColumnDimension('R')->setWidth(50);
    //设置第一栏的标题
    $objSheet->setCellValue('A1', 'ID')
        ->setCellValue('B1', '图片');
//            ->setCellValue('C1', '标题')
//            ->setCellValue('D1', '价格')
//            ->setCellValue('E1', '类型')
//            ->setCellValue('F1', '省')
//            ->setCellValue('G1', '市')
//            ->setCellValue('H1', '区')
//            ->setCellValue('I1', '街道')
//            ->setCellValue('J1', '地址')
//            ->setCellValue('K1', '面积')
//            ->setCellValue('L1', '押金类型')
//            ->setCellValue('M1', '联系人名称')
//            ->setCellValue('N1', '联系人电话')
//            ->setCellValue('O1', '联系人微信')
//            ->setCellValue('P1', '房源类型')
//            ->setCellValue('Q1', '描述')
//            ->setCellValue('R1', '备用多图');
    // 第二行起，每一行的值，setCellValueExplicit是用来导出文本格式的
    foreach ($data as $key => $val) {
        $key = $key + 2;
        $objSheet->setCellValue('A' . $key, $val['id']);
//                ->setCellValue('B' . $key, $val['avatar']);
//                ->setCellValue('C' . $key, $val['title'])
//                ->setCellValue('D' . $key, $val['price'])
//                ->setCellValue('E' . $key, $val['is_sale'])
//                ->setCellValue('F' . $key, $val['province_name'])
//                ->setCellValue('G' . $key, $val['city_name'])
//                ->setCellValue('H' . $key, $val['region_name'])
//                ->setCellValue('I' . $key, $val['street_name'])
//                ->setCellValue('J' . $key, $val['address'])
//                ->setCellValue('K' . $key, $val['area'])
//                ->setCellValue('L' . $key, $val['deposit_type_name'])
//                ->setCellValue('M' . $key, $val['user']['user_nickname'])
//                ->setCellValue('N' . $key, $val['user']['mobile'])
//                ->setCellValue('O' . $key, $val['user']['mobile'])
//                ->setCellValue('P' . $key, $val['house_type_id'])
//                ->setCellValue('Q' . $key, $val['desc']);

        $num = 10;
        // 多图导出
        if (!empty($val['avatar'])) {
            $images = $val['avatar'];
            foreach ($images as $k => $v){

                $img = cutOutUrl($v)['del_url'];
                // 过滤非文件类型
                if (is_file($img)) {
                    // 引入操作图片类
                    $drawings[$key] = new Drawing();
                    $drawings[$key]->setResizeProportional(false); // TODO 此处顺序不可调，因为导出默认是按原图像缩放的，设置成false才可以设置成可控制的宽度，要注意哦！
                    $drawings[$key]->setName('备用多图');
                    $drawings[$key]->setDescription('备用多图');
                    $drawings[$key]->setPath($img);
                    $drawings[$key]->setWidth(60);
                    $drawings[$key]->setHeight(60);
                    $drawings[$key]->setOffsetX($num);
                    $drawings[$key]->setOffsetY(10);
                    $drawings[$key]->setCoordinates('B' . $key);
                    $drawings[$key]->setWorksheet($objSheet);
                }
                $num = $num + 70; // 增加每张图之间的间距
            }
        }
        else
        {
            $objSheet->setCellValue('R' . $key, '');
        }
    }
    downloadExcel($newExcel, '数据表', 'Xlsx');
}
# 公共文件，用来传入xls并下载
function downloadExcel($newExcel, $filename, $format)
{
    // $format只能为 Xlsx 或 Xls
    if ($format == 'Xlsx') {
        $contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
    } elseif ($format == 'Xls') {
        $contentType = 'pplication/vnd.ms-excel';
    }
    ob_end_clean();
    $filenameurl = $filename . date('Y-m-d') . '.' . strtolower($format);
    header("Content-Disposition: attachment;filename=" . $filename . date('Y-m-d') . '.' . strtolower($format));
    $objWriter = IOFactory::createWriter($newExcel, $format);
    $objWriter->save('php://output');
    exit;
}

/**
 * 导出excel表
 * $data：要导出excel表的数据，接受一个二维数组
 * $name：excel表的表名
 * $head：excel表的表头，一维数组
 * $key：$data中对应表头的键的数组，一维数组
 * 备注：表头（对应列数）不能超过26；
 */
function exportExcel($name='表名', $data=[], $head=[], $keys=[])
{
    $spreadsheet = new Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();
    //$sheet->getDefaultColumnDimension()->setAutoSize(true);// 列宽
    $sheet->getDefaultColumnDimension()->setWidth(30);//设置默认列宽
    // $sheet->getDefaultRowD$spreadsheet->getProperties()

    $sheet->setTitle($name);//设置当前工作表标题

    //设置表头
    foreach ($head as $key => $value) {
        $sheet->setCellValueByColumnAndRow($key+1, 1, $value);
    }

    //设置内容
    foreach ($data as $row=>$item) {
        foreach ($keys as $key=>$value) {
             $sheet->setCellValueByColumnAndRow($key+1, $row+2, $item[$value]." ");
        }
    }
    $writer = new Xlsx($spreadsheet);
	$writer->setPreCalculateFormulas(false); //禁用公式预计算
    ///分批量导出/////////////////
   /* $li = '';
    if($client_count>10000){
         $sum = $client_count/10000;
         echo "数据过大，需要分批导出<hr>";
         $li = '总数据'.$client_count.'条，分：'.ceil($sum).'批导出，每次最多10000条<hr>';
        for($i=0;$i<ceil($sum);$i++){
            $pi = $i+1;
            $result = 'page='.($pi).'&limit=10000';
            $file_name = "第{$pi}批数据";
            $url = 'https://mtlj.xxxx.com/index.php/admin/download/exportExcel2?'.$result.'&type='.$type.'&dateArr0='.$dateArr0.'&dateArr1='.$dateArr1;
            $li .= '<a href='.$url.' target="_bank">'.$file_name.'</a><hr><br>';
        }
        echo $li;
    }else{
        $this->exportExcel2(0,10000,$type,$dateArr0,$dateArr1);
    }
    */
    //合并单元格 合并后，赋值只能给A1，开始的坐标。
    // $sheet->mergeCells('A2:A3');//合并单元格
    //$sheet->mergeCellsByColumnAndRow(1,2,1,3);//使用数字单元格坐标合并单元格
    // $sheet->unmergeCellsByColumnAndRow(1,2,1,3);//使用数字单元格坐标拆分单元格

    //1.下载到服务器
    //$writer->save($name.'.xlsx');

    //2.输出到浏览器
    //header('Content-Type: application/vnd.ms-excel');//xls
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');//xlsx
    header('Content-Disposition: attachment;filename="'.$name.'.xlsx"');
    header('Cache-Control: max-age=0');

    $writer->save('php://output');
    //删除清空：
    $spreadsheet->disconnectWorksheets();
    unset($spreadsheet);
    exit;
}

/**
 * 生成账号和加密密码
 * @param $admin_name string 用户名
 * @param $admin_password string 密码
 * @param $admin_create_time 创建时间
 *
 **/
function set_password(string $name,string $password){
    $data = [];
    $data['admin_name'] = $name;
    $data['admin_status'] = 0;
    $data['admin_password'] = password_hash($password,PASSWORD_DEFAULT);
    $data['admin_create_time'] = date("Y-m-d H:i:s",time());
    return $data;
}

/**
 * 验证密码
 * @param $input_password 输入的密码
 * @param  $user_password 用户数据库密码
*/
function checkPassword(string $input_password,string $user_password){
    if(password_verify(trim($input_password),$user_password)){
        return ['status'=>200,'msg'=>"验证正确"];
    }else{
        return ['status'=>500,'msg'=>"验证错误"];
    }
}

/**
 * 生成验签
 * @param $uid 用户id
 * @param $key 自定义的一个随机字串用户于加密中常用的 盐  salt
 * @return mixed
 */
function signToken($uid,$key='abcdefg'){
    $token = array(
        "iss" => $key,
        //"aud" => $id,//接收人，也就是发给谁
        "iat" => time(),//签发时间,当前时间
        "nbf" => time()+3,//生效时间,在生成时间后一点点
        'exp' => time()+10800,//过期时间，三个小时
        'data'=> ['uid'=>$uid]//自定义信息
    );

    //  print_r($token);
    $jwt = JWT::encode($token, $key, "HS256");  //生成了 token
    return $jwt;
}

/**
 * 验证token
 * @param $token
 * @param $key 自定义的一个随机字串用户于加密中常用的 盐  salt
 * @return array|int[]
 */
function checkToken($token,$key='abcdefg'){
    $result["token"] = $token;
    try {
        //延长有效期1分钟
        JWT::$leeway = 60;
        //对token解码，得到的一个对象，所以直接转成数组
        $data = (array)JWT::decode($token,new Key($key, 'HS256'));
        //获取token里面的相关信息并赋值给数据集
        $result['data'] = $data['data'];
        //定义Result变量的status字段
        $result['status'] = 10001;
        //验证通过后返回$result数据集
        return $result;
        //如果验证失败，catch以下错误
    }catch (SignatureInvalidException $exception){
        //定义result数据集状态码status和data的默认值
        $result['status'] = 10002;
        $result['data']   = '验证失败！请重新登录';
        return $result;
    }catch (BeforeValidException $exception){
        //定义result数据集状态码status和data的默认值
        $result['status'] = 10003;
        $result['data']   = 'token未生效，请稍后！';
        return $result;
    }catch (ExpiredException $exception){
        //定义result数据集状态码status和data的默认值
        $result['status'] = 10004;
        $result['data']   = '登录过期，请重新登录！';
        return $result;
    }catch (Exception $exception){
        //定义result数据集状态码status和data的默认值
        $result['status'] = 10005;
        $result['data']   = '未知错误，请重新登录！';
        return $result;
    }
}

/**
 * 生成二维码海报 (执行后直接输出显示)
 *
 * @param string $bg_filename 背景图片文件名, 可以是网络图片
 * @param string $qrcode_filename 二维码图片文件名, 可以是网络图片
 * @param integer $qrcode_width 二维码定义宽度
 * @param integer $qrcode_height 二维码定义高度
 * @param integer $x 二维码距左边
 * @param integer $y 二维码距顶边
 * @return void
 */
function out_poster(string $bg_filename, string $qrcode_filename, int $qrcode_width, int $qrcode_height, int $x, int $y)
{
    $stream_opts = [
        "ssl" => [
            "verify_peer"=>false,
            "verify_peer_name"=>false,
        ]
    ];
    // 背景图file_get_contents($url, false, stream_context_create($stream_opts));
    $bg_im = imagecreatefromstring(file_get_contents($bg_filename,false,stream_context_create($stream_opts)));

    // 二维码
    $qrcode_blob = file_get_contents($qrcode_filename,false,stream_context_create($stream_opts));
    $qrcode_im = imagecreatefromstring($qrcode_blob);
    list($width_orig, $height_orig) = getimagesizefromstring($qrcode_blob);

    // 缩放二维码
    $new_qrcode = imagecreatetruecolor($qrcode_width, $qrcode_height);
    imagecopyresampled($new_qrcode, $qrcode_im, 0, 0, 0, 0, $qrcode_width, $qrcode_height, $width_orig, $height_orig);
    imagedestroy($qrcode_im);


    // 透明度
    $alpha = 100;

    // 合并图片
    imagecopymerge($bg_im, $new_qrcode, $x, $y, 0, 0, $qrcode_width, $qrcode_height, $alpha);

    // 合并输出格式
    header('Content-type: image/jpeg');

    imagejpeg($bg_im);
    // 释放资源
    imagedestroy($bg_im);
    imagedestroy($new_qrcode);
    exit;
}



